/**
 * Created by IPE on 2016/12/28.
 */
var ws = null;
var url = 'ws://' + window.location.host + "/websocket";
var transports = [];
connect();

function setConnected(connected) {
    document.getElementById('echo').disabled = !connected;
}

function connect() {
    ws = new WebSocket(url);

    ws.onopen = function () {
        setConnected(true);
        log('已连接');
    };
    ws.onmessage = function (event) {
        var msg = event.data;
        console.log(msg)
        var obj = $.parseJSON(msg);

        //chat收取处理
        if (obj.type == "chat")log(obj.sendUser + ":" + obj.message);

        //pop收取处理
        if (obj.type == "pop") {
            var topList = obj.topList;
            $("#pop_console").empty();
            $.each(topList, function(index, value, array) {
                pop_log(value.key,value.value)
            });
            if(topList.length>12)$('#pop_echo').prop('disabled',true);
        }
    };

    ws.onclose = function (event) {
        log('连接关闭');
    };
}

function disconnect() {
    if (ws != null) {
        ws.close();
        ws = null;
    }
    setConnected(false);
}

function echo() {
    if (ws != null) {
        var message = document.getElementById('message').value;
        textSend(message);
        $('#message').val("")
    } else {
        alert('未连接');
    }
}

$('#pop_message').keydown(function(e){
    if(e.keyCode==13&&$('#pop_echo').prop('disabled')!=true){
        pop_echo();
    }
})


$('#message').keydown(function(e){
    if(e.keyCode==13&&$('#echo').prop('disabled')!=true){
        echo();
    }
})

function log(message) {
    var console = document.getElementById('console');
    var p = document.createElement('p');
    p.style.wordWrap = 'break-word';
    p.appendChild(document.createTextNode(message));
    console.appendChild(p);
    while (console.childNodes.length > 100) {
        console.removeChild(console.firstChild);
    }
    console.scrollTop = console.scrollHeight;
}

function pop_log(message, num) {
    var console = $('#pop_console');
    var d = $("<div class='pop_item'></div>");
    var t = $("<div>" + message + "</div>")
    var bt = $("<button type='button'></button>")
    bt.click(function () {
        popSend(message)
    })
    bt.text(num)
    var sp = $("<span class='glyphicon glyphicon-thumbs-up'></span>")
    d.append(t)
    d.append(bt)
    bt.append(sp)
    console.append(d)
}


function checkLeave() {
    textSend("关闭了连接")
    disconnect();
}

function pop_echo() {
    if (ws != null) {
        var message = document.getElementById('pop_message').value;
        if(message=="")return
        popSend(message);
        $('#pop_message').val("")
    } else {
        alert('未连接');
    }
}

function textSend(text) {
    var map = {type: "chat", message: text};
    var json = JSON.stringify(map)
    ws.send(json)
}

function popSend(text) {
    var map = {type: "pop", message: text};
    var json = JSON.stringify(map)
    ws.send(json)
}